package com.jml.log;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

@Component
public class LogContainer {
    // 队列原则 先进先出 后进后出原则  从队列中获取到日志内容 该日志就会从队列中移除
    private static BlockingDeque<String> dequeLogs = new LinkedBlockingDeque<>();
    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    public LogContainer() {
        new LogSendKafkaThread().start();
    }

    public void add(String log) {
        dequeLogs.offer(log);
    }

    //单独创建一个线程
    class LogSendKafkaThread extends Thread {
        @Override
        public void run() {
            while (true) {
                String log = dequeLogs.poll();
                if (!StringUtils.isEmpty(log)) {
                    kafkaTemplate.send("jml-log", log);
                }

            }
        }
    }

}
